import os

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.conf import settings
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import permission_required

from dynamic import app_settings

def available_repositories(request):
    ret = []

    root_path = os.path.abspath(app_settings.DYNAMIC_REPOSITORY_ROOT) + os.sep
    git_path = root_path + app_settings.DYNAMIC_REPOSITORY_GIT_PATH
    svn_path = root_path + app_settings.DYNAMIC_REPOSITORY_SUBVERSION_PATH
    bzr_path = root_path + app_settings.DYNAMIC_REPOSITORY_BAZAAR_PATH

    if os.path.isdir(git_path): ret.append(('git', git_path))
    if os.path.isdir(svn_path): ret.append(('svn', svn_path))
    if os.path.isdir(bzr_path): ret.append(('bzr', bzr_path))

    return ret

def index_git(request):
    import PyGIT

    git = PyGIT.Storage(request.session.get('dynamic.repository.path'))

    return {'repository': git}

@permission_required('dynamic.can_manage_repository')
def index(request):
    params = {}
    availables = available_repositories(request)

    if not len(availables):
        request.user.messages_set.create(_('There is no repository available. You must have git, subversion or bazaar repository in your project path.'))
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '../'))
    elif len(availables) == 1:
        request.session['dynamic.repository.current'] = availables[0][0]
        request.session['dynamic.repository.path'] = availables[0][1]

    if request.GET.get('choose_repository') in ('git','svn','bzr'):
        request.session['dynamic.repository.current'] = request.GET.get('choose_repository')
        request.session['dynamic.repository.path'] = dict(availables)[request.GET.get('choose_repository')]
        return HttpResponseRedirect(request.path)

    if request.session.get('dynamic.repository.current') == 'git':
        params = index_git(request)

    params['title'] = _('Dynamic Repository Integration')
    params['settings'] = settings
    params['app_settings'] = app_settings
    params['availables'] = availables
    params['current_repository'] = request.session.get('dynamic.repository.current')
    params['current_path'] = request.session.get('dynamic.repository.path')

    return render_to_response(
            'dynamic/repository/index.html',
            params,
            context_instance=RequestContext(request),
            )

